DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Core Jetty
refcard cover
Refcard #154

Core Jetty

A Lightweight, Open-Source Web Server and Servlet Container

Includes architecture, configuration, basic, and advanced usage, with many code examples.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Jos Dirksen
Architect, atos origin
Table of Contents
► Introduction ► Jetty Architecture ► Configuring Jetty ► Basic Usage ► Advanced Usage ► Using with Web Frameworks ► Running Standalone ► Integration with Maven
Section 1

Introduction

By Jos Dirksen

Jetty, an open-source web server hosted by the Eclipse foundation, is a full-fledged HTTP server and Servlet container that can be easily configured to serve static and dynamic content. You can very easily embed Jetty into your own applications using Java or XML-based configuration or run Jetty directly from Maven. Additionally, you can use Jetty in many different high-demand areas such as Yahoo Hadoop Cluster, Google AppEngine, and Yahoo! Zimbra. This RefCard refers primarily to Jetty 8; however, most of the configuration discussed will work on Jetty 7.

Section 2

Jetty Architecture

It's important to understand the architecture behind Jetty. The main architecture of Jetty consists out of the following four components.

“Architecture

Server

The server is the container class for all the other components of the architecture. A server contains a number of connectors that listen on a specific port and accepts connections (e.g., HTTP, HTTPS, or AJP13) from clients. A server also contains a set of handlers that process the client requests from the connectors and produce responses that are returned to the client. Threads retrieved from the configured threadpool do this processing.

Connector

Jetty provides a number of connectors that accept requests from clients to be processed by the handlers. Jetty comes with the following set of default connectors.

Connector Description and Usage
SocketConnector Uses blocking IO and normal JRE sockets. Onethread is allocated per connection. Only use
when NIO connector isn't available.
BlockingChannelConnector Uses NIO buffers with a blocking thread model.One thread is allocated per connection. Use
when there are few very active connections.
SelectChannelConnector Uses NIO buffers with a non-blocking threading model. Threads are only allocated to connections with requests. Use when there are many connections that have idle periods.
SslSocketConnector SSL version of the SocketConnector
SslSelectChannelConnector SSL version of the SelectChannelConnector
AJPConnector Use for connections from Apache modules: mod_proxy_ajp and mod_jk.
HTTPSPDYServerConnector Supports the SPDY protocol and performs SPDY to HTTP conversion. If SPDY is not negotiated,
falls back to HTTPS.

Handler

The handler is the component that deals with requests received by a
connector. There are three types of handlers in Jetty.

  • Coordinating handlers route requests to other handlers.

  • Filtering handlers modify a request and pass it on to other
    handlers.

  • Generating handlers create content.

  • Jetty provides the following handlers.
Name Description
ConnectHandler Implements a tunneling proxy that supports HTTP CONNECT.
DebugHandler Writes details of the request and response to an outputstream.
GzipHandler Will gzip the response
IPAccessHandler Provides access control using white/black lists on IP addresses
and URLs.
RequestLogHandler Allows logging of requests to a request log.
ResourceHandler Serves static content and handles If-Modified-Since headers.
Doesn't handle 404 errors.
RewriteHandler Allows you to rewrite the URL, cookies, headers, and status
codes based on a set of rules.
ConstraintSecurity-
Handler
Enforces security constraints based on Servlet specification 2.4.
StatisticsHandler Collects statistics on requests and responses.
WebSocketHandler Provides support for the websockets protocol.
HandlerCollection Contains a collection of handlers. Handlers are called in order.
ContextHandlerCollection

Contains a collection of handlers. Handlers are called based on
the provided context and virtual host.

HandlerList Like HandlerCollection, but calls each handler in turn until an
exception is thrown, the response is committed, or a positive
status is set.
ServletHandler Maps requests to servlets that implement the HttpServlet API.
ServletContextHandler See ServletHandler. Allows you to specify the context the servlet
is mapped to.
DefaultHandler Deals with unhandeld requests from the server.
WebAppContext Can be used to map requests to a web application (WAR).

Threadpool

The threadpool provides threads to the handlers, the work done by the connnectors and the handlers. Jetty comes with the following threadpools.

Name Description
ExecutorThreadPool Uses the standard java ThreadPoolExecutor to execute jobs.
QueuedThreadPool Uses a blocking queue to execute jobs.
Section 3

Configuring Jetty

When you configure Jetty, you create and configure a set of connectors and handlers. You can do this using XML or plain java.


XML Configuration

Jetty provides an XML-based configuration language based on the Java Reflection API. When starting Jetty with an XML configuration, Jetty will parse this XML and create and configure the specified objects. The following is a basic configuration using the XML syntax with a server, connector, handler, and threadpool.

​x
1
​
2
<Configure id="Server" class="org.eclipse.jetty.server.Server">
3
<Set name="threadPool">
4
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
5
<Set name="minThreads">10</Set>
6
<Set name="maxThreads">10</Set>
7
</New>
8
</Set>
9
<Call name="addConnector">
10
<Arg>
11
<New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
12
<Set name="port">8080</Set>
13
</New>
14
</Arg>
15
</Call
16
<Set name="handler">
17
<New class="org.eclipse.jetty.server.handler.HandlerList">
18
<Set name="handlers">
19
<Array type="org.eclipse.jetty.server.Handler">
20
<Item>
21
<New class="org.eclipse.jetty.server.handler.ResourceHandler">
22
<Set name="directoryListed">true</Set>
23
<Set name="resourceBase">./files</Set>
24
</New>
25
</Item>
26
<Item>
27
<New class="org.eclipse.jetty.server.handler.DefaultHandler"/>
28
</Item>
29
</Array>
30
</Set>
31
</New>
32
</Set>

This code creates a ResourceHandler that shows the files from the "./files" directory. The DefaultHandler takes care of the unhandled request. You can start this server using the following java code:

10
1
​
2
  Public class JettyExample {
3
  public static void main(String[] args) throws Exception {
4
  Resource fileCfg = Resource.newSystemResource("example.xml");
5
  XMLConfiguration config = new
6
  XMLConfiguration(fileCfg.getInputStream());
7
  Server.start();
8
  Server.join();
9
  }
10
 }

The following elements can be used to configure Jetty.

XML Element Description
Configure The root element that specifies the class to be configured.
Attribute "id": reference to created object.
Attribute "class": FQN to instantiate.
Can contain: <Set>, <Get>, <Put>, <Call>, <New>, <Ref>, <Array>,
<Map>, <Property>
Set Maps to a call to a setter method.
Attribute "name": Setter to call
Attribute "type": Type of argument
Attribute "class": if present, make a static call to the specified class.
Can contain: <Get>, <Call>, <New>, <Ref>, <Array>, <Map>, <SystemProperty>,
<Property>
Get

Maps a call to a getter method.
Attribute "name": getter to call
Attribute "class": if present, make a static call to the specified class.
Attribute "id": reference to returned object
Can contain: <Set>, <Get>, <Put>, <Call>, <New>, <Ref>, <Array>,
<Map>, <Property>

Put Calls the put method on the current object that should implement
Map.
Attribute "name": used as put key
Attribute "type": force type of value
Can contain: <Get>, <Call>, <New>, <Ref>, <Array>, <Map>, <SystemProperty>,
<Property>
Call Makes an arbitrary call to the current object.
Attribute "name": method to call
Attribute "class": if present, make a static call to the specified class.
Attribute "id": reference to returned object
Can contain: <Arg>, <Set>, <Get>, <Put>, <Call>, <New>, <Ref>,
<Array>, <Map>, <Property>
Arg Specifies an argument for <Call> and <New>
Attribute "type": force type of value
Can contain: <Get>, <Call>, <New>, <Ref>, <Array>, <Map>, <SystemProperty>,
<Property>
New Instantiates a new object.
Attribute "id": reference to created object.
Attribute "class": FQN to instantiate.
Can contain: <Arg>, <Set>, <Get>, <Put>, <Call>, <New>, <Ref>,
<Array>, <Map>, <Property>
Ref References a previously created Object.
Attribute "id": the object to reference to.
Can contain: <Set>, <Get>, <Put>, <Call>, <New>, <Ref>, <Array>,
<Map>, <Property>
Array Allows creation of new array.
Attribute "type": the type of array.
Attribute "id": reference to the created array Can contain: <Item>
Item Defines an entry for an Array or Map element.
Attribute "type": force the type of the item
Attribute "id": reference to the created item.
Can contain: <Get>, <Call>, <New>, <Ref>, <Array>, <Map>, <SystemProperty>,
<Property>
Map Allows creation new new HashMap.
Attribute "id": reference to the created map.
Can contain: <Entry>
Entry

Contains a key-value <Item> pair
Can contain: <Item>

SystemProperty Gets the value of a JVM system property.
Attribute "name": the name of the property
Attribute "default": default value as fallback
Attribute "id": reference to the created object
Can contain: nothing
Property Allows arbitrary properties to be retrieved by name.
Attribute "name": the name of the property
Attribute "default": default value as fallback
Attribute "id": reference to the created object
Can contain: <Set>, <Get>, <Put>, <Call>, <New>, <Ref>, <Array>,
<Map>, <Property>

Java Configuration

Using java for the configuration of your Jetty server is very simple and is done in the same manner as we've shown for the XML configuration. Instead of using the XML elements to instantiate the objects, you can now do this directly from java. You can rewrite the previous XML configuration to the following piece of java.

20
1
public static void main(String[] args) throws Exception {
2
  Server server = new Server();
3
  QueuedThreadPool pool = new QueuedThreadPool();
4
  pool.setMinThreads(10);
5
  pool.setMaxThreads(10);
6
  server.setThreadPool(pool);
7
  SelectChannelConnector connector = new SelectChannelConnector();
8
  connector.setPort(8080);
9
  server.addConnector(connector);
10
  HandlerList handlers = new HandlerList();
11
  ResourceHandler resourceHandler = new ResourceHandler();
12
  resourceHandler.setDirectoriesListed(true);
13
  resourceHandler.setResourceBase("./files");
14
  DefaultHandler defaultHandler = new DefaultHandler();
15
  handlers.setHandlers(new Handler[]
16
  {resourceHandler, defaultHandler});
17
  server.setHandler(handlers);
18
  server.start();
19
  server.join();
20
 }

Hot Tip

Since Jetty components are simple POJOs, you can also use your dependency injection framework of choice to set up the Jetty server. An example with Spring is shown here: http://wiki.eclipse.org/Jetty/Howto/Spring
Section 4

Basic Usage

This section describes how to use Jetty for a number of basic use cases.

Serving Static Content

scripting to change bar colors on a chart based on plotted data. When running Jetty as an embedded web server in your own application, it can be useful to be able to serve static content (e.g., documentation). The easiest way to server static content is by using a ResourceHandler:

4
1
<New class="org.eclipse.jetty.server.handler.ResourceHandler">
2
  <Set name="directoryListed">true</Set>
3
  <Set name="resourceBase">./files</Set>
4
 </New>

The ResourceHandler can be configured with the following properties:

Property Description
aliases Boolean; if true symlinks are followed.
directoryListed Boolean; if true show directory listings.
welcomeFiles String[]; a welcome file is shown for a directory if it matches an
item from the supplied String[].
resourceBase String: The path from where to serve content.

If you want the ResourceHandler to listen on a specific context, you can wrap this Handler in a ContextHandler:

6
1
<New class="org.eclipse.jetty.server.handler.ContextHandler">
2
  <Set name="contextPath">/documentation</Set>
3
  <Set name="handler">
4
  <New class="...ResourceHandler">...</New>
5
  </Set>
6
 </New>

SSL Configuration

To configure Jetty to use HTTPS, you can use one of the SSL-enabled connectors: SslSelectChannelConnector or SSLSocketConnector. The following listing defines two-way ssl (client authentication):

17
1
Call name="addConnector">
2
  <Arg>
3
  <New class="org.eclipse...SslSelectChannelConnector">
4
  <Arg>
5
  <New class="org.eclipse.jetty.http.ssl.SslContextFactory">
6
  <Set name="keyStore">etc/keystore</Set>
7
  <Set name="keyStorePassword">OBF:1vny1zlo1x8e1vnw1</Set>
8
  <Set name="keyManagerPassword">OBF:1u2u1wml1z7s1z/Set>
9
  <Set name="trustStore">/etc/keystore</Set>
10
  <Set name="trustStorePassword">OBF:w11x8g1zlu1vn4</Set>
11
  <Set name="needClientAuth">true</Set>
12
  </New>
13
  </Arg>
14
  <Set name="port">8443</Set>
15
  </New>
16
  </Arg>
17
 </Call>

The following properties are used:

Property Description
keystore Keystore for the server keypair
keystorepassword Password for the keystore
keymanagerpassword Password for the private key
truststore Keystore for trusted certificates
truststorepassword Password for truststore
needClientAuth True, if clients must use a certificate

There are more advanced properties available. For these, see the Javadocs for the SslContextFactory.

Hot Tip

Jetty provides a utility that you can use to secure passwords in configuration files. By using the org.eclipse.jetty.http.security.Passwd class, you can generate obfuscated, checksummed, and encrypted passwords.

Servlets and the ServletContextHandler

Jetty allows you to easily configure servlets without having to use a web. xml. To do this, you can use a ServletContextHandler, which allows for easy construction of a context with a ServletHandler. The following properties can be set on a ServletContextHandler.

Property Description
contextPath The base context path used for this ServletContextHandler.
allowNullPathInfo If "false", then /context is redirected to /context/.
compactPath If "true", replace multiple '/'s with a single '/'.
errorHandler An "ErrorHandler" determines how error pages are handled.
securityHandler The "SecurityHandler" to use for this ServletContextHandler.
sessionHandler The "SessionHandler" to use for this ServletContextHandler
welcomeFiles List of welcomeFiles to show for this context.

A servlet on this context can be added using the addServlet operation (which can also be done through XML).

3
1
addServlet(String className,String pathSpec)
2
  addServlet(Class<? extends Servlet> servlet,String pathSpec)
3
 addServlet(ServletHolder servlet,String pathSpec)

Using Existing WAR Files and Layout

Jetty allows you to directly use existing WAR files (and exploded WAR files) through the WebAppContext. This is especially useful during development.

Directly from a WAR:

5
1
Server server = new Server(8080);
2
  WebAppContext webapp = new WebAppContext();
3
  webapp.setContextPath("/");
4
  webapp.setWar(jetty_home+"/webapps/test.war");
5
 server.setHandler(webapp);

From an Exploded WAR (e.g During Development):

7
1
Server server = new Server(8080);
2
  WebAppContext context = new WebAppContext();
3
  context.setDescriptor(webapp+"/WEB-INF/web.xml");
4
  context.setResourceBase("../test-jetty-webapp/src/main/webapp");
5
  context.setContextPath("/");
6
  context.setParentLoaderPriority(true);
7
 server.setHandler(context);

You can also configure a WebAppContext in jetty.xml using the XMLbased configuration or in a context.xml file.

Security Realms

Security Realms allow you to protect your web applications. Jetty provides a number of standard LoginServices you can use to secure your web application.

Property Description
HashLoginService A simple implementation that stores users and roles in memory
and loads them from a properties file.
JDBCLoginService Retrieves users and roles from a database configured with JDBC.
DataSourceLogin-
Service
Retrieves users and roles from a javax.sql.DataSource.
JAASLoginService

Delegates the login to JAAS. Jetty provides the following JAAS
modules:
• DBCLoginModule
• PropertyFileLoginModule
• DataSourceLoginModule
• LdapLoginModule

To use a LoginServices, you configure it in the jetty.xml file.

9
1
<Call name="addBean">
2
  <Arg>
3
  <New class="org.eclipse.jetty.security.HashLoginService">
4
  <Set name="name">RefCardRealm</Set>
5
  <Set name="config">etc/realm.properties</Set>
6
  <Set name="refreshInterval">0</Set>
7
  </New>
8
  </Arg>
9
 </Call>

The real-name defined in the jetty.xml can now be referenced from the web.xml.

8
1
<login-config>
2
  <auth-method>FORM</auth-method>
3
  <realm-name>RefCardRealm</realm-name>
4
  <form-login-config>
5
  <form-login-page>/login/login</form-login-page>
6
  <form-error-page>/login/error</form-error-page>
7
  </form-login-config>
8
 </login-config>

JNDI Usage

Jetty has support for java:comp/env lookups in web applications.

Setup JNDI

The JNDI feature isn't enabled by default. To enable JNDI, you have to set the following configurationClasses on your WebAppContext or WebAppDeployer:

15
1
Configure id="wac" class="org.eclipse.jetty.webapp.WebAppContext">
2
  <Array id="plusConfig" type="java.lang.String">
3
  <Item>org.eclipse.jetty.webapp.WebInfConfiguration</Item>
4
  <Item>org.eclipse.jetty.webapp.WebXmlConfiguration</Item>
5
  <Item>org.eclipse.jetty.webapp.MetaInfConfiguration</Item>
6
  <Item>org.eclipse.jetty.webapp.FragmentConfiguration</Item>
7
  <Item>org.eclipse.jetty.plus.webapp.EnvConfiguration</Item>
8
  <Item>org.eclipse.jetty.plus.webapp.PlusConfiguration</Item>
9
  <Item>org.eclipse.jetty.webapp.JettyWebXmlConfiguration</Item>
10
  <!-- next one not needed for Jetty 8 -->
11
  <Item>org.eclipse.jetty.webapp.TagLibConfiguration</Item>
12
  </Array>
13
  <Set name="war">location/of/webapp</Set>
14
  <Set name="configurationClasses"><Ref id="plusConfig"/></Set>
15
 </Configure>

You can now use , , and entries in your web.xml to point to resources stored in the JNDI context.

Binding Objects to JNDI

Jetty allows you to bind POJOs, a java.naming.Reference instance, an implementation of java.naming.Referenceable, and a link between a name in the web.xml and one of these other objects. These objects can be configured from Java or in the jetty.xml configuration files.

5
1
<New class=type of naming entry>
2
  <Arg>scope</Arg>
3
  <Arg>name to bind as</Arg>
4
  <Arg>the object to bind</Arg>
5
 </New>

The scope defines where the object is visible. If left empty, the scope is set to the Configure context this entry is defined in. This scope can also be set to point to a specific server of webapplication.

1
1
<Arg><Ref id='wac'/></Arg>

The following environment types are supported:

Type How to bind from Jetty
env-entry <New class="org.eclipse.jetty.plus.jndi.EnvEntry">
<Arg></Arg>
<Arg>mySpecialValue</Arg>
<Arg type="java.lang.Integer">4000</Arg>
<!—set to true to override web.xml -->
<Arg type="boolean">true</Arg>
</New>
resource-ref resourceenv-
ref
<New id="myds" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref id="wac"/></Arg>
<Arg>jdbc/myds</Arg>
<Arg>
<New class="org...EmbeddedDataSource">
<Set name="DatabaseName">test</Set>
<Set name="createDatabase">create</Set>
</New>
</Arg>
</New>
Link With a Link you can link a resource from the web.xml to a
resource in the containter context.
<New id="map1" class="org.eclipse.jetty.plus.jndi.Link">
<Arg><Ref id='wac'/></Arg>
<Arg>jdbc/datasourceInWeb</Arg>
<Arg>jdbc/nameInContainer</Arg>
</New>

Jetty-env.xml

You can store environment settings in a jetty.xml file that is stored in your WEB-INF directory.

3
1
<Configure class="org.mortbay.jetty.webapp.WebAppContext">
2
  <!-- Add entries only valid for this webapp -->
3
 </Configure>
Section 5

Advanced Usage

This section describes a couple of advanced configurations for Jetty.

Integration with CDI

When creating applications, it's very useful to use context and dependency injection (CDI). With JEE6, this is a standard feature of an application server. You can also use CDI with Jetty. The following configuration can be used to configure Weld (the CDI reference implementation) for a specific web application on Jetty.

14
1
<Configure id="webAppCtx"
2
   class="org.eclipse.jetty.webapp.WebAppContext">
3
   <New id="BManager" class="org.eclipse.jetty.plus.jndi.Resource">
4
   <Arg><Ref id="webAppCtx"/></Arg>
5
   <Arg>BeanManager</Arg>
6
   <Arg>
7
   <New class="javax.naming.Reference">
8
   <Arg>javax.enterprise.inject.spi.BeanManager</Arg>
9
   <Arg>org.jboss.weld.resources.ManagerObjectFactory</Arg>
10
   <Arg/>
11
   </New>
12
   </Arg>
13
   </New>
14
 </Configure>

The beanmanager is available on java:comp/env/BeanManager.

Running Jetty Behind a Reverse Proxy

Jetty can be configured to run behind a reverse proxy, such as Apache with mod_proxy or mod_proxy_ajp. The preferred way is to use mod_ proxy with a normal HTTP connector. However, it's also possible to create a connector for the AJP protocol used by the mod_proxy_ajp modules.

7
1
<Call name="addConnector">
2
<Arg>
3
<New class="org.eclipse.jetty.ajp.Ajp13SocketConnector">
4
<Set name="port">8009</Set>
5
</New>
6
</Arg>
7
</Call>

For more information on running Jetty as a reverse proxy, see: http:// wiki.eclipse.org/Jetty/Howto/Configure_mod_proxy

Websockets

Jetty has support for websockets. You can create your own websockets servlet by extending WebSocketServlet.

26
1
public class ExampleWSServlet extends WebSocketServlet {
2
  protected void doGet(HttpServletRequest request,
3
  HttpServletResponse response)
4
  throws ServletException ,IOException {
5
  getServletContext().getNamedDispatcher("default")
6
  .forward(request,response);
7
  }
8
  protected WebSocket doWebSocketConnect(
9
  HttpServletRequest request, String protocol) {
10
  return new ExampleWebSocket();
11
  }
12
  class ExampleWebSocket implements WebSocket {
13
  private Outbound outbound;
14
  public void onConnect(Outbound outbound) {
15
  this.outbound=outbound;
16
  }
17
  public void onMessage(byte frame
18
  ,byte[] data,int offset, int length) {
19
  // handle binary data
20
  }
21
  public void onMessage(byte frame, String data) {
22
  // handle String data
23
  }
24
  public void onDisconnect() {}
25
  }
26
 }

Session Clustering

Jetty uses two components for session management. First, a session ID manager ensures that the session IDs are unique across all web applications. Second, a session manager handles the session lifecycle. If you want to cluster your sessions, Jetty provides a JDBC-based SessionIDManager and SessionManager.

Configure the JDBCSessionIdManager:

3
1
JDBCSessionIdManager idMgr = new JDBCSessionIdManager(server); idMgr.setWorkerName("fred"); idMgr.
2
  setDriverInfo("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/sessions?user=janb"); idMgr.setScavengeInterval(60);
3
 server.setSessionIdManager(idMgr);

This JDBCSessionIdManager needs to be configured on each cluster node with a unique workerName. Once you've defined this ID manager, you can can configure the JDBCSessionManager.

4
1
WebAppContext wac = new WebAppContext();
2
  … //configure your webapp context
3
  JDBCSessionManager jdbcMgr = new JDBCSessionManager(); jdbcMgr.setIdManager(server.getSessionIdManager());
4
  wac.setSessionHandler(jdbcMgr);


Hot Tip

Besides the JDBC-based managers, you can also use MongoDB for session clustering. For this clustering solution, you configure the MongoDBSessionIDManager and the MongoSessionManager".

SPDY Support

SPDY is an experimental protocol whose goal it is to reduce the latency of web pages. Jetty can support this protocol through the HTTPSPDYServerConnector class.

15
1
<Configure id="Server" class="org.eclipse.jetty.server.Server">
2
  <New id="sslContextFactory" class="...util.ssl.SslContextFactory">
3
  <Set name="keyStorePath">your_keystore.jks</Set>
4
  <Set name="keyStorePassword">storepwd</Set>
5
  <Set name="protocol">TLSv1</Set>
6
  </New>
7
  <Call name="addConnector">
8
  <Arg>
9
  <New class="..http.HTTPSPDYServerConnector">
10
  <Arg><Ref id="sslContextFactory"/></Arg>
11
  <Set name="Port">8443</Set>
12
  </New>
13
  </Arg>
14
  </Call>
15
  </Configure>
Section 6

Using with Web Frameworks

This section shows how to run an application based on a number of popular Java web frameworks using an embedded Jetty. This is especially useful during development for a quick compile-build-test cycle or when you want to run your application in a debugger with hot-code replace. If your favorite web application framework isn't listed here, these examples should point you in the right direction to get Jetty working with your framework.

JSF 2.0

JSF2 scans the WEB-INF/classes directories for beans. Before you can use an embedded Jetty to directly launch a JSF application, you have to make sure you configure your project to output its class files to the WEB-INF/ classes directory in your project. After that, you can use the standard WebAppContext to run your JSF 2.0 web application directly from Jetty.

5
1
WebAppContext handler = new WebAppContext();
2
  handler.setResourceBase("src/main/webapp");
3
  handler.setDescriptor("src/main/webapp/WEB-INF/web.xml");
4
  handler.setContextPath("/");
5
 handler.setParentLoaderPriority(true);

Spring Web

Spring Web can be run directly from an exploded WAR file using a standard WebAppContext (see GWT). You can also configure the Spring DispatcherServlet directly.

10
1
ServletContextHanderl context = new ServletContextHandler
2
  (server, "/", Context.SESSIONS);
3
  DispatcherServlet dispatcherServlet = new DispatcherServlet();
4
  dispatcherServlet.setContextClass(
5
  AnnotationConfigWebApplicationContext.class);
6
  ServletHolder holder = new ServletHolder(dispatcherServlet);
7
  holder.setInitOrder(1);
8
  context.addServlet(holder, "/example/*");
9
  context.setInitParameter("contextConfigLocation"
10
 ,"classpath*:resources/spring/*.xml");

This context can be added as a handler to a server instance.

Grails

Grails already provides Jetty functionality out of the box. To run grails using an embedded Jetty container, you can use the grails run-app command.

Wicket

To run Wicket from Jetty, you can configure the WicketServlet with the applicationClassName you want to start.

7
1
ServletContextHandler context = new ServletContextHandler
2
  (server, "/", Context.SESSIONS);ServletHolder ServletHolder holder = new ServletHolder(new WicketServlet());
3
  holder.setInitParameter(
4
  "applicationClassName","dzone.refcard.Application");
5
  // set init order to initialize when handler starts
6
  holder.setInitOrder(1);
7
 context.addServlet(servletHolder, "/*");

This context can be added as a handler to a server instance.

GWT, Vaadin and Tapestry

You can directly run a GWT or a Vaadin application from an exploded WAR file using a standard WebAppContext.

5
1
WebAppContext handler = new WebAppContext();
2
  handler.setResourceBase("./apps/TheGWTApplication");
3
  handler.setDescriptor("./apps/TheGwtApplication/WEB-INF/web.xml");
4
  handler.setContextPath("/");
5
 handler.setParentLoaderPriority(true);

This context can be added as a handler to a server instance.

Section 7

Running Standalone

If you want to configure the standard Jetty distribution and not run Jetty embedded from your own application, you can configure Jetty using the following XML files.

File Description
jett.xml Main configuration file. Configures a Server class. Normally located
in $JETTY_HOME/etc/jetty.xml
jetty-web.xml Configure a web application context. Located in the WEB-INF directory
of a specific web application.
jetty-env.xml Allows you to configure JNDI resources for a web application.
Located in the WEB-INF directory of a web application.
webdefault.xml Set default values on a web application context that will be applied
to all web applications. This is loaded before the web.xml is processed.
Located in ${jetty.home}/etc/webdefault
override-web.xml Jetty applies the configuration in this file after the web.xml from a
web application is parsed. This file is located in the WEB-INF directory
of a web application

More information on running Jetty standalone can be found at the Jetty Wiki: http://wiki.eclipse.org/Jetty/Feature/Start.jar

Section 8

Integration with Maven

Jetty is also often used in a maven build file to easily run and test a webapp project. When running from Maven, you can configure Jetty using the configuration elements provided by the plugin.

XML Element Description
connectors List of connectors objects. If not specified, a SelectChannelConnector
will be configured on port 8080.
jettyXML Location of a jetty.xml configuration file. Use this for objects that
can't be configured from the plugin.
scanIntervalSeconds Interval to check for changes to the webapp. If a change is
detected, the webapp is redeployed.
systemProperties Sets system properties that are used during the execution of the
plugin.
systemPropertiesFile Loads system properties from a file. These properties are available
during the execution of the plugin.
loginServices A list of LoginService implementations that are available to the
webapp.
requestLog Configures an implementation of a RequestLog.
webApp Configures the webapplication. You can use any of the setters
of the WebAppContext to configure your web application.For
instance:
<contextHandlers>
<contextHandler
implementation="..WebAppContext">
<war>${basedir}../../another.war</war>
<contextPath>/other</contextPath>
</contextHandler>
</contextHandlers>

The Jetty plugin defines the following goals.

Goal Description
jetty:run Runs a web application from the maven default project locations.
Resources are served from ${basedir}/src/main/webapp, "Classes"
from ${project.build.outputdirectory} and the web.xml from ${basedir}/
src/main/webapp/WEB-INF
jetty:run-war Packages the web application and deploys it to Jetty.
jetty:run-exploded Packages your web application into an exploded WAR file and
deploys it to Jetty.
jetty:deploy-war Similar to jetty:run-war, but without assembling the WAR file.
jetty:run-forked Runs Jetty and the web application in a new JVM.
jetty:start Starts Jetty without building any WAR or compiling classes.

For a complete overview of the available options look at the documentation for the Jetty maven plugin at: http://wiki.eclipse.org/ Jetty/Feature/Jetty_Maven_Plugin

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

7,600 OSS Projects Per Company
related article thumbnail

DZone Article

How to Choose a Container Registry: The Top 9 Picks
related article thumbnail

DZone Article

How to Convert XLS to XLSX in Java
related article thumbnail

DZone Article

Automatic Code Transformation With OpenRewrite
related refcard thumbnail

Free DZone Refcard

Platform Engineering Essentials
related refcard thumbnail

Free DZone Refcard

The Essentials of GitOps
related refcard thumbnail

Free DZone Refcard

Continuous Integration Patterns and Anti-Patterns
related refcard thumbnail

Free DZone Refcard

Getting Started With CI/CD Pipeline Security

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: